<template>
  <div class="educontrol-login">
    <!-- <img src="../../../public/images/futureClassroom.png" class="futureClassroom" alt="未来教室logo"> -->
    <header>
      <div class="head-cont clear">
        <div class="logo fl">
          <img v-if="logo_url" :src="BASE_URL + logo_url" alt="logo" />
        </div>
      </div>
    </header>
    <div class="i_signIn">
      <div class="content">
        <img class="bg" src="../../../public/images/zhuce_bgc.png" alt="登录背景图">
        <div class="login_form fr">
          <div class="icon">
            <img src="../../../public/images/logo_i.png" alt="icon">
          </div>

          <el-form :model="loginForm" :label-position="top" label-width="0" :rules="rules" ref="loginForm"
            class="clear">
            <el-form-item prop="account" class="l-user" label="账号">
              <el-input clearable v-model.trim="loginForm.account" placeholder="请输入用户帐号/绑定的手机号" @focus="focusAccount"
                @change="changeAccount">
                <template v-if="accountArr.length > 0">
                  <i class="el-icon-arrow-down el-input__icon" slot="suffix" @click="clearAccount"
                    v-show="!showAccountArr">
                  </i>
                  <i class="el-icon-arrow-up el-input__icon" slot="suffix" @click="clearAccount"
                    v-show="showAccountArr">
                  </i>
                </template>
                <!-- <template slot="prepend"><img src="../../../public/images/account.png" alt="账号图标"></template> -->
              </el-input>
              <transition name="el-fade-in-linear">
                <div class="l-autocomplete" v-if="accountArr.length > 0" v-show="showAccountArr">
                  <ul>
                    <template v-for="(item, index) of accountArr">
                      <li :key="index" @click.self="setAccount(item)" v-if="index < 3">
                        <span>{{ item.value }}</span>
                        <i class="el-icon-error" @click.self="removeAccount(item, index)"> </i>
                      </li>
                    </template>

                  </ul>
                </div>
              </transition>


            </el-form-item>
            <el-form-item prop="pwd" label="密码">
              <el-input v-model.trim="loginForm.pwd" type="password" :maxlength="16"
                @keyup.13.stop.native.prevent="submitForm()" placeholder="请输入登录密码">
                <!-- <template slot="prepend"><img src="../../../public/images/pwd.png" alt="密码图标"></template> -->
              </el-input>
            </el-form-item>
            <!-- <el-checkbox class="fl" v-model="loginForm.savePwd">记住密码</el-checkbox> -->
            <span class="fr" @click="retrieve">忘记密码</span>

            <el-form-item class="login">
              <el-button type="primary" :disabled="isDisabled" @click.stop.prevent="submitForm()">登录</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>


    <foote />
  </div>
</template>

<script>
import store from "../../store/index.js";
import Global from '../../tools/global.js'; // 引入global.js
import { Base64 } from 'js-base64';
import { setTimeout } from 'timers';
import foote from "../common/footer";

export default {
  components: {
    foote
  },
  data() {
    return {
      showAccountArr: false,
      logo_url: null,
      icon_url: null,
      loginForm: {
        account: '',
        pwd: '',
        savePwd: false,
      },
      accountArr: [],   // 存放已记住密码的用户信息
      selectInput: '',
      rules: {
        account: [
          { required: true, message: '请输入账号名称', trigger: ['change'] },
          { min: 4, max: 30, message: '长度在 4 到 30 个字符', trigger: ['change'] }
        ],
        pwd: [
          { required: true, message: '请输入登录密码', trigger: ['change'] },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: ['change'] },
          { pattern: /^[\w+]{6,16}$/, message: '密码由6~16位英文、数字、下划线组成', trigger: 'blur' },
        ]
      }
    }
  },
  created() {
    sessionStorage.setItem('decisionPlatform', 'home');
    this.icon_url = sessionStorage.getItem("logoUrl")
    // console.log('======', this.logoUrl)
    // this.get_access_token();
    this.homeLogo();
    this.checkLogin();
  },
  mounted() {
    let arr = localStorage.getItem('loginUser') ? JSON.parse(localStorage.getItem('loginUser')) : [];   // 已登录过的用户信息

    if (arr.length > 0) {
      // 获取当前时间戳
      let now = Date.now();

      // 第一次遍历验证是否有的登录信息已经保存超过30天，若是把timeStamp重置为false
      arr.forEach(item => {
        if (now - item.timeStamp >= 30 * 24 * 60 * 60 * 1000) {
          item.timeStamp = false
        }
      })

      // 第二次遍历返回时间小30天的登录信息数组
      arr = arr.filter(item => {
        item.psw = Base64.decode(item.psw);
        return item.timeStamp
      })

      this.accountArr = arr

      if (arr.length > 0) {
        this.loginForm = {
          account: arr[0].value,
          pwd: arr[0].psw,
          savePwd: true,
        }
      }
    }

  },
  computed: {
    isDisabled() {
      let account = '';

      if (is_empty(this.loginForm.account)) {
        if (is_empty(this.selectInput)) {
          account = this.loginForm.account;
        } else {
          account = this.selectInput;
        }
      } else {
        account = this.loginForm.account;
      }

      if ((account.length > 3 && account.length < 31) && (this.loginForm.pwd.length > 5 && this.loginForm.pwd.length < 17)) {
        return false;
      }

      return true;
    }
  },
  methods: {
    homeLogo() {
      let success = (res) => {
        this.logo_url = res.data[0].f_logo;
        sessionStorage.setItem('main_logo_url', this.logo_url);
      };
      this.$ajax({
        url: "api/system/get_logo",
        method: "get",
        params: {},
        func: { success: success },
      });
    },
    /**
     * 账号为空同时清空密码框
     * @DateTime 2020-03-25T17:04:45+0800
     * @qiu_m
     * @param    {[type]}                 val [description]
     * @return   {[type]}                     [description]
     */
    changeAccount(val) {
      val == '' ? this.loginForm.pwd = '' : val
    },
    /**
     * 触发焦点隐藏登录用户列表
     * @DateTime 2020-03-25T17:05:24+0800
     * @qiu_m
     * @return   {[type]}                 [description]
     */
    focusAccount() {

      this.showAccountArr = false
    },
    /**
     * 显示隐藏登录用户列表
     * @DateTime 2020-03-25T17:06:52+0800
     * @qiu_m
     * @return   {[type]}                 [description]
     */
    clearAccount() {
      this.showAccountArr = !this.showAccountArr
    },
    /**
     * 根据参数改变登录用户
     * @DateTime 2020-03-25T17:07:11+0800
     * @qiu_m
     * @param    {[type]}                 obj [登录信息]
     */
    setAccount(obj) {

      this.loginForm.account = obj.value;
      this.loginForm.pwd = obj.psw;
      this.showAccountArr = false
    },
    /**
     * 删除保存的用户账号
     * @DateTime 2020-03-25T16:16:40+0800
     * @qiu_m
     * @param    {[type]}                 obj   [用户账号密码]
     * @param    {[type]}                 index [索引]
     * @return   {[type]}                       [description]
     */
    removeAccount(obj, index) {

      if (obj.value == this.loginForm.account) {
        this.loginForm.account = '';
        this.loginForm.pwd = '';
      }

      this.accountArr.splice(index, 1);
      localStorage.setItem('loginUser', JSON.stringify(this.accountArr))

    },
    // 清除账号的时候吧密码也一并清除
    clearPsw() {
      this.loginForm.pwd = '';
      this.loginForm.savePwd = false;
    },
    /**
     * 判断 PC 或 手机端登录
     */
    getUseHls() {
      let success = res => {
        if (res.data === "yes") {
          window.location.href = sessionStorage.getItem('host_addr') + '/wap';
        } else {
          this.checkLogin();
        }
      };
      let fail = (res => { })

      this.$ajax.get('api/login/get_use_hls', { func: { success: success, fail: fail } })
    },
    // 初始化页面是获取AccessToken
    get_access_token() {
      this.$ajax.get('/accessToken', {
        params: {
          company: 'BL',
          device_name: 'TE-0600R',
          data: {
            client_id: Global.client_id,
            secret: Global.secret
          }
        }
      })
        .then(response => {
          let data = response.data.data;
          Global.access_token = data.access_token;
          localStorage.setItem('token', Global.access_token);

          this.getUseHls();
        });
    },
    /**
     * 查询登录情况
     */
    checkLogin() {
      let success = res => {
        setTimeout(() => {
          // location.href = sessionStorage.getItem('host_addr') + '/home';
          this.$router.push('/home');
        }, 500)
      };
      let fail = (res => { })

      this.$ajax.get('api/login/login', { func: { success: success, fail: fail } })
    },
    handleSelect(item) {

      this.loginForm.pwd = item.psw;
      this.loginForm.savePwd = true;
    },
    handleIconClick(ev) {
      console.log(ev, 8);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    querySearch(queryString, cb) {
      var accountArr = this.accountArr;
      var results = queryString ? accountArr.filter(this.createFilter(queryString)) : accountArr;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    /**
     * 获取下拉框的搜索值
     */
    // filterVal(val) {
    //     this.selectInput = val;
    // },
    /**
     * 聚焦的时候情况数据
     */
    // selectFocus() {
    //     this.selectInput = '';
    //     this.loginForm.account = '';
    // },
    // blur(e){
    //     if (is_empty(e.target.value)) {
    //         if (is_empty(this.selectInput)) {
    //             this.loginForm.account = e.target.value;
    //         } else {
    //             this.loginForm.account = this.selectInput;
    //         }
    //     } else {
    //         this.loginForm.account = e.target.value;
    //     }

    //     this.selectInput = '';
    // },
    retrieve() {
      this.$router.push('/retrieve')
    },
    // 选择已记住密码用户的方法
    chosen(val) {
      this.loginForm.account = val;

      let user = this.accountArr

      for (let i = 0; i < user.length; i++) {
        if (user[i].value == val) {
          this.loginForm.pwd = user[i].psw;
          this.loginForm.savePwd = true;
          break
        }
      }
    },
    // 点击清空用户信息是执行
    clear() {
      this.loginForm.savePwd = false;
      this.loginForm.pwd = '';
    },
    // 登录并获取用户信息
    submitForm() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {

          const success = (res => {
            if (res.status == "success") {
              sessionStorage.setItem('token', res.data);
              // 登录操作成功提示
              this.$message.success('登录成功!')

              // 根据是否勾选记住密码进行用户信息的缓存操作
              let login_arr = this.accountArr,
                login_before = false,
                index = -1;

              // 遍历当前用户是否已经有过记住密码的记录
              for (let i = 0; i < login_arr.length; i++) {
                if (login_arr[i].value == this.loginForm.account) {
                  index = i;
                  login_before = true;
                  break
                }
              }

              // 若有勾选记住密码则执行
              if (this.loginForm.savePwd == true) {

                if (!login_before) {
                  // 如果保存的用户信息已有3个或以上，则直接删除最近没有登录过的信息
                  if (login_arr.length >= 3) {
                    login_arr.pop()
                  }

                  // 把当前登录的用户信息放在数组第一位
                  login_arr.unshift({
                    value: this.loginForm.account,
                    psw: this.loginForm.pwd,
                    timeStamp: Date.now()
                  })

                  // localStorage.setItem('loginUser', JSON.stringify( login_arr ))

                } else {

                  // 若之前已经保存过当前登录信息，则把当前的信息提前到数组的第一位，并且更新密码
                  if (login_arr.length >= 2) {
                    login_arr.splice(index, 1)[0]
                    login_arr.unshift({
                      value: this.loginForm.account,
                      psw: this.loginForm.pwd,
                      timeStamp: Date.now()
                    });

                  }

                }

              } else {

                // 若没有勾选记住密码并且之前存有登录信息，则把之前的登录信息去掉
                if (login_before) {
                  login_arr.splice(index, 1)
                }

              }

              let initArr = deep_clone(login_arr);

              login_arr.forEach(item => item.psw = Base64.encode(item.psw));

              localStorage.setItem('loginUser', JSON.stringify(login_arr))

              this.accountArr = initArr;
              localStorage.setItem('logintoken', res.data.token)

              this.getUseInfo();
            }
          })
          let params = {
            usernum: this.loginForm.account,
            userpassword: this.loginForm.pwd
          }

          this.$ajax.post('api/login/login', params, { func: { success: success } })
        } else {
          return false;
        }
      });
    },
    /**
     * 获取用户信息
     */
    getUseInfo() {
      const success = (res => {
        sessionStorage.setItem('decisionPlatform', 'manage');
        let data = res.data;

        // 缓存获取到的用户信息
        sessionStorage.setItem('user_info_str', JSON.stringify(data.userinfo));
        sessionStorage.setItem("manage_url", data.manage_url);
        sessionStorage.setItem("personal_url", data.personal_url);
        sessionStorage.setItem("ItcJwtToken", data.userinfo.ItcJwtToken);
        store.commit("SET_USERINFO", data.userinfo);
        this.$g.user_id = data.userinfo.id;
        if (data.userinfo.class) {
          sessionStorage.setItem('class_id', data.userinfo.class[0].id);

        }
        var routerData = this.checkRouter();
        this.$router.addRoutes(routerData);

        let host = sessionStorage.getItem("host");
        let token = localStorage.getItem("logintoken");

        if (typeof data.manage != "undefined" && data.manage != null && data.manage != "") {
          // if (process.env.NODE_ENV === "development") {
          this.$router.push('/home');
          // } else {
          //     setTimeout(() => {
          //         location.href = `http://${host}/admin/login?token=${token}&protocol=http&host=${host}`;
          //     }, 1000)
          // }

        } else {
          this.$router.push('/home');

          // 直接 push 导致账号设置的路由没有载入，所以需要刷新页面
          // location.href = sessionStorage.getItem('host_addr') + '/home';
        }
      })

      this.$ajax.get('api/login/login', { func: { success: success } })
    },
  },
}
</script>

<style lang="scss">
.educontrol-login {
  height: 100%;
  width: 100%;
  position: absolute;

  header {
    background: #fff;
    height: 90px;
    position: relative;


    .logo {
      width: 190px;
      height: 50px;
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      margin: auto 280px;
    }
  }

  .i_signIn {
    height: calc(100% - 134px);
  }

  .content {

    background: #ffffff;
    position: relative;
    height: 700px;

    .bg {
      width: 100%;
      position: relative;
      height: 700px;
      object-fit: cover;
      background-size: 100% 100%;
    }
  }

  .login_form {
    position: absolute;
    width: 300px;
    height: 480px;
    background: #ffffff;
    top: 0;
    right: 17%;
    padding: 0 50px;
    margin: auto;
    bottom: 0;



    .icon {
      text-align: center;
      margin: 30px 0 10px 0;
    }

    >p {
      margin-bottom: 26px;
      padding-top: 103px;
      height: 20px;
      line-height: 20px;
      font-size: 14px;
      font-weight: bold;
      font-family: MicrosoftYaHei-Bold, MicrosoftYaHei;
      color: #fff;
    }

    .login {
      text-align: center;

      button {
        margin-top: 30px;
        background-color: #0064FF;
        width: 140px !important;
        border-radius: 40px;
        border: none;
      }
    }

    .el-form {
      .el-form-item__label {
        float: none;
        color: #333333;
      }

      .el-input {
        border: 0; // 去除未选中状态边框
        outline: none; // 去除选中状态边框
      }

      .el-form-item {

        .el-input__inner {
          // background-color: #00132F;
          border: none;
          border-bottom: 1px solid #ddd;
        }

        &:last-child {
          margin-top: 60px;

          >div>button {
            width: 100%;
          }
        }

        img {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background: #A1C5E9;
        }


        .el-select {
          position: absolute;
          left: 42px;
          width: 264px;
          height: 40px;

          .el-input input {
            border-top-left-radius: 0;
            border-bottom-left-radius: 0;
          }

        }


        .el-autocomplete {
          width: 100%;
        }

      }

      // .fl {
      //     width: 48px;
      //     height: 16px;
      //     font-size: 12px;
      //     font-family: MicrosoftYaHei;
      //     color: rgba(102, 102, 102, 1);
      //     line-height: 16px;
      // }

      .fr {
        width: 48px;
        height: 16px;
        font-size: 12px;
        font-family: MicrosoftYaHei;
        color: #25B2FF;
        line-height: 16px;
        cursor: pointer;



      }

    }


  }
}
</style>